package com.paranoid.flashcard.dao;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import org.json.JSONArray;
import org.json.JSONObject;

import android.database.Cursor;
import android.util.Log;

import com.paranoid.flashcard.dao.RestClient.RequestMethod;
import com.paranoid.flashcard.model.Deck.DownloadStatus;
import com.paranoid.flashcard.model.Deck.Featured;
import com.paranoid.flashcard.model.QuizletCard;
import com.paranoid.flashcard.model.QuizletDeck;

public class QuizletDao {
	
	private static QuizletDao instance;
	
	public static QuizletDao getInstance() {
		if (instance == null)
			instance = new QuizletDao();
		return instance;
	}
	
	private QuizletDao() {
	}
	

	public Cursor getFeaturedDecks() {
		FlashcardDao dao = FlashcardDao.getInstance(null);
		return dao.getFeaturedDecks();
	}
	
	public Cursor downloadFeaturedDecks() {
        long featured[] = {1910600, 2190673, 432915, 2091637, 1991805, 1942274, 2026496, 1957625, 2190814};
        
        List<QuizletDeck> result = getDecksById(featured);
        FlashcardDao dao = FlashcardDao.getInstance(null);
        for (QuizletDeck deck : result) {
            try {
                dao.insertDeck(deck.id, deck.title, 0, DownloadStatus.REMOTE, Featured.YES);
            } catch (Exception ex) {
                Log.i("", "insert exception" + ex.getMessage());
            }
        }
        return dao.getFeaturedDecks();
	}
	
	private List<QuizletDeck> getDecksBySearchTerm(String term) {
		return getDecks(term, "most_studied", "on", "off");
	}
	
	private List<QuizletDeck> getDecksById(long...ids) { 
		StringBuilder queryString = new StringBuilder("ids:");
		for (long id : ids) {
			queryString.append(""+id+",");
		}
		queryString.deleteCharAt(queryString.length()-1);
		
		return getDecks(queryString.toString(), "alphabetical", "off", "off");
	}
	
	private List<QuizletDeck> getDecks(String searchTerm, String sort, String imagesOnly, String extended) {
        try {
        	String response = executeRestQuery(searchTerm, sort, imagesOnly, extended);
        	JSONArray a = getSets(response);
        	ArrayList<QuizletDeck> result = new ArrayList<QuizletDeck>();
        	for (int i=0; i<a.length(); i++) {
        		JSONObject deckObject = a.getJSONObject(i);
        		result.add(getQuizletDeck(deckObject));
        	}
        	return result;
        } catch (Exception ex) {
        	Log.e("", ex.getMessage());
        	return new ArrayList<QuizletDeck>();
        }
	}
	
	public List<QuizletDeck> removeAlreadyDownloadedDecks(List<QuizletDeck> deckList) {
		FlashcardDao dao = FlashcardDao.getInstance(null);
		List<QuizletDeck> remove = new ArrayList<QuizletDeck>();
		for (QuizletDeck deck : deckList) {
			if (dao.getDeckById(deck.id) != null)
				remove.add(deck);
		}
		deckList.removeAll(remove);
		return deckList;
	}
	
	private JSONArray getSets(String response) throws Exception {
    	JSONObject jsonObject = new JSONObject(response);
    	JSONArray result = jsonObject.getJSONArray("sets");
    	return result;
	}
	
	private QuizletDeck getQuizletDeck(JSONObject object) throws Exception {
		QuizletDeck result = new QuizletDeck();
		
		result.title = object.getString("title");
		result.id = object.getLong("id");
		result.url = object.getString("url");
		result.creator = object.getString("creator");
		result.created = new Date(object.getLong("created"));
		result.termCount = object.getInt("term_count");
		result.hasImages = object.getString("has_images").equals("true") ? true : false;
		result.lastModified = new Date(object.getLong("last_modified"));
		
		return result;
	}
	
	private String executeRestQuery(String searchTerm, String sort, String imagesOnly, String extended) throws Exception {
		RestClient client = new RestClient("http://api.quizlet.com/1.0/sets");
        client.AddParam("dev_key", "cg8ydYHq6j5a4RDC");
        client.AddParam("whitespace", "on");
        
        client.AddParam("q", searchTerm);
        client.AddParam("sort", sort);
        client.AddParam("images_only", imagesOnly);
        client.AddParam("extended", extended);

    	client.Execute(RequestMethod.GET);
        
        String result = client.getResponse();
		return result;
	}
	
	public void importDeckToDb(QuizletDeck deck) {
		List<QuizletCard> cards = getCardsForDeck(deck.id);
		FlashcardDao.getInstance(null).insertQuizletDeck(deck, cards);
	}
	
	public static List<QuizletCard> getCardsForDeck(long quizletId) {
		RestClient client = new RestClient("http://api.quizlet.com/1.0/sets");
        client.AddParam("dev_key", "cg8ydYHq6j5a4RDC");
        client.AddParam("q", "ids:"+quizletId);
        client.AddParam("whitespace", "on");
        client.AddParam("extended", "on");
        
        
        try {
        	client.Execute(RequestMethod.GET);
        } catch (Exception ex) {
        	Log.e("", ex.getMessage());
        	return null;
        }
        Log.i("", "Message = " + client.getResponse());
        try {
        	JSONObject j = new JSONObject(client.getResponse());
        	Log.i("", "response_type: " + j.getString("response_type"));
        	Log.i("", "sets_with_images: " + j.getInt("sets_with_images"));
        	JSONArray a = j.getJSONArray("sets");
        	JSONObject j2 = a.getJSONObject(0);
        	JSONArray a2 = j2.getJSONArray("terms");
        	ArrayList<QuizletCard> result = new ArrayList<QuizletCard>();
        	for (int i=0; i<a2.length(); i++) {
        		JSONArray j3 = a2.getJSONArray(i);
        		QuizletCard r = new QuizletCard();
        		r.term = j3.getString(0);
        		r.def = j3.getString(1);
        		r.img = j3.getString(2);
        		result.add(r);
        		Log.i("", "Term: " + j3.getString(0));
        		Log.i("", "Def: " + j3.getString(1));
        		Log.i("", "Image: " + j3.getString(2));
        	}
        	return result;
        } catch (Exception ex) {
        	Log.e("", ex.getMessage());
        	return null;
        }
	}
	
}
